package rabbitMQ.publish;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitMQ.common.Common;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost(Common.HOST);//ip
        factory.setPort(Common.PORT);//端口号
        factory.setVirtualHost(Common.VIRTUALHOST);//虚拟机名称
        factory.setUsername(Common.USERNAME);//用户名
        factory.setPassword(Common.PASSWORD);//密码
        //3. 创建连接connection
        Connection connection = factory.newConnection();

        //创建channel
        Channel channel = connection.createChannel();

        //创建交换机
        channel.exchangeDeclare(Common.FANOUT_EXCHANGE, BuiltinExchangeType.FANOUT, true, false, false, null);
        //创建队列
        channel.queueDeclare(Common.FANOUT_QUEUE1, true, false, false, null);
        channel.queueDeclare(Common.FANOUT_QUEUE2, true, false, false, null);
        //绑定交换机和队列
        channel.queueBind(Common.FANOUT_QUEUE1, Common.FANOUT_EXCHANGE, "");
        channel.queueBind(Common.FANOUT_QUEUE2, Common.FANOUT_EXCHANGE, "");
        //发送消息
        String msg = "hello, fanout......";
        channel.basicPublish(Common.FANOUT_EXCHANGE, "", null, msg.getBytes(StandardCharsets.UTF_8));
    }
}
